import { Injectable } from '@nestjs/common';
import { exec as execCb } from 'child_process';
import { promisify } from 'util';

const exec = promisify(execCb);

@Injectable()
export class ShellService {
  async runCommand(command: string, args: string[] = []): Promise<string> {
    try {
      // 拼接完整命令
      const fullCommand = `${command} ${args.join(' ')}`;

      // 执行命令
      const { stdout, stderr } = await exec(fullCommand, { encoding: 'utf8' });

      if (stderr) {
        throw new Error(stderr);
      }
      return stdout.trim(); // 去掉多余的换行符
    } catch (error) {
      throw new Error(`Command failed: ${error.message}`);
    }
  }
}
